<template>
  <div class="app-container">
    <h4 class="form-header h4">基本信息</h4>
    <el-form ref="formData" :model="formData" label-width="80px" label-position="top" :rules="rules">
      <el-row>
        <el-col :span="6" :offset="2">
          <el-form-item label="申请人" prop="createUserName">
            <el-input v-model="formData.createUserName" disabled />
          </el-form-item>
          <el-form-item label="申请人id" prop="createUserId" v-if="false" >
            <el-input v-model="formData.createUserId" />
          </el-form-item>
        </el-col>
        <el-col :span="6" :offset="2">
          <el-form-item label="申请人所在部门" prop="createDeptName">
            <el-input  v-model="formData.createDeptName" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="6" :offset="2">
          <el-form-item label="申请时间" prop="createTime">
            <el-date-picker v-model="formData.createTime" format="yyyy-MM-dd" value-format="yyyy-MM-dd HH:mm:ss" placeholder="请选择申请时间" disabled></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>

        <el-col :span="8" :offset="2">
          <el-form-item label="需求日期" prop="demandTime">
            <el-date-picker v-model="formData.demandTime" format="yyyy-MM-dd" value-format="yyyy-MM-dd HH:mm:ss" placeholder="请选择需求日期" clearable></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8" :offset="2">
          <el-form-item label="需求类型" prop="demandType">
            <el-radio-group v-model="formData.demandType" size="medium">
              <el-radio v-for="(item, index) in demandTypeOptions" :key="index" :label="item.value"
                        :disabled="item.disabled">{{item.label}}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="18" :offset="2">
          <el-form-item label="采购计划事由" prop="procurePlanReason">
            <el-input v-model="formData.procurePlanReason" type="textarea" placeholder="请输入采购计划事由"
                      :autosize="{minRows: 4, maxRows: 4}"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-divider content-position="center">采购计划明细信息</el-divider>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddAProcurePlanDetail">添加</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteAProcurePlanDetail">删除</el-button>
        </el-col>
      </el-row>
      <el-table :data="aProcurePlanDetailList" :row-class-name="rowAProcurePlanDetailIndex" @selection-change="handleAProcurePlanDetailSelectionChange" ref="aProcurePlanDetail">
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="序号" align="center" prop="index" width="50"/>
        <el-table-column label="产品名称" prop="productName" width="300" align="center">
          <template slot-scope="scope">
            <el-input v-model="scope.row.productName" placeholder="请输入产品名称" />
          </template>
        </el-table-column>
        <el-table-column label="产品类型" prop="productCategory" width="300" align="center">
          <template slot-scope="scope">
            <el-cascader
              v-model="scope.row.productCategory"
              :options="productCategoryOptions"
              :props="field101Props"
              @change="handleChange(scope.row,...arguments)"
              :style="{width: '100%'}"
              placeholder="请选择产品类型"
              filterable clearable/>
          </template>
        </el-table-column>
        <el-table-column label="大类" prop="largeCategoryCode" width="150" v-if="false">
          <template slot-scope="scope">
            <el-input v-model="scope.row.largeCategoryCode" placeholder="请输入大类" />
          </template>
        </el-table-column>
        <el-table-column label="中类" prop="middleCategoryCode" width="150" v-if="false">
          <template slot-scope="scope">
            <el-input v-model="scope.row.middleCategoryCode" placeholder="请输入中类" />
          </template>
        </el-table-column>
        <el-table-column label="小类" prop="smallCategoryCode" width="150" v-if="false">
          <template slot-scope="scope">
            <el-input v-model="scope.row.smallCategoryCode" placeholder="请输入小类" />
          </template>
        </el-table-column>

        <el-table-column label="规格型号" prop="specificationModle" width="300" align="center">
          <template slot-scope="scope">
            <el-input v-model="scope.row.specificationModle" placeholder="请输入规格型号" />
          </template>
        </el-table-column>
        <el-table-column label="计量单位" prop="measurementUnit" width="300" align="center">
          <template slot-scope="scope">
            <el-input v-model="scope.row.measurementUnit" placeholder="请输入计量单位" />
          </template>
        </el-table-column>
        <el-table-column label="单价（元）" prop="unitPrice" width="300" align="center">
          <template slot-scope="scope">
            <el-input-number v-model="scope.row.unitPrice" :precision="2" :step="0.1" :min="0.1" :max="99999" placeholder="请输入单价"  @change="setBudgetAmount(scope.row)"/>
          </template>
        </el-table-column>
        <el-table-column label="采购数量" prop="procureQuantity" width="300" align="center">
          <template slot-scope="scope">
            <el-input-number v-model="scope.row.procureQuantity" :min="1" :max="9999" placeholder="请输入采购数量" @change="setBudgetAmount(scope.row)"/>
          </template>
        </el-table-column>
        <el-table-column label="预算金额（元）" prop="budgetAmount" width="300" align="center">
          <template slot-scope="scope">
            <el-input-number v-model="scope.row.budgetAmount" :precision="2" :step="0.1" :max="999999999" placeholder="请输入预算金额" disabled/>
          </template>
        </el-table-column>
        <el-table-column label="采购用途" prop="procurePurpose" width="300" align="center">
          <template slot-scope="scope">
            <el-select v-model="scope.row.procurePurpose" clearable placeholder="请选择采购用途" >
              <el-option
                v-for="dict in dict.type.a_procure_purpose"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="产品线" prop="productLineId" width="300" align="center">
          <template slot-scope="scope">
            <el-input v-model="scope.row.productLineId" placeholder="请输入产品线主键id" />
          </template>
        </el-table-column>
        <el-table-column label="备注" prop="remarks" width="300" align="center">
          <template slot-scope="scope">
            <el-input type="textarea" v-model="scope.row.remarks" placeholder="请输入备注" />
          </template>
        </el-table-column>
      </el-table>
      <el-form-item style="text-align: center;margin-left:-120px;margin-top:30px;">
        <el-button type="primary" @click="submitForm()">提交</el-button>
        <el-button @click="close()">返回</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import {addPlan} from '@/api/asset/plan'
import {categoryCascaderQuery} from '@/api/asset/category'
export default {
  components: {},
  props: [],
  dicts: ['a_procure_purpose'],
  data() {
    return {
      formData: {
        createUserId:undefined,
        createUserName: undefined,
        createDeptName: undefined,
        createTime: null,
        demandTime: null,
        demandType: 0,
        procurePlanReason: undefined,
      },
      // 子表选中数据
      checkedAProcurePlanDetail: [],
      // 采购计划明细表格数据
      aProcurePlanDetailList: [],
      productCategoryOptions: [],
      field101Props: {
        "multiple": false
      },
      rules: {
        createUserName: [{
          required: true,
          message: '请输入申请人',
          trigger: 'blur'
        }],
        createDeptName: [{
          required: true,
          message: '请输入申请人所在部门',
          trigger: 'blur'
        }],
        createTime: [{
          required: true,
          message: '请选择申请时间',
          trigger: 'blur'
        }],
        demandTime: [{
          required: true,
          message: '请选择需求日期',
          trigger: 'blur'
        }],
        demandType: [{
          required: true,
          message: '需求类型不能为空',
          trigger: 'blur'
        }],
        procurePlanReason: [],
      },
      demandTypeOptions: [{
        "label": "自采",
        "value": 0
      }, {
        "label": "租赁",
        "value": 1
      }],
    }
  },
  computed: {},
  watch: {},
  created() {
    //进页面默认赋值
    this.handleAddAProcurePlanDetail();
    this.formData.createUserId  = this.$store.state.user.id;
    this.formData.createUserName= this.$store.state.user.nickName;
    this.formData.createDeptName= this.$store.state.user.dept.deptName;
    this.formData.createTime = this.getNowTime(true);
    this.categoryCascaderQuery();
  },
  mounted() {

  },
  methods: {
    /** 查询产品类别级联关系 */
    categoryCascaderQuery() {
      categoryCascaderQuery().then(response => {
        this.productCategoryOptions = response.data;
      });
    },
    //选中事件
    handleChange(row,value) {
      row.largeCategoryCode = value[0];
      row.middleCategoryCode = value[1];
      row.smallCategoryCode = value[2];
      // 这里处理选择变化的逻辑
    },
    setBudgetAmount(row){
      let budgetAmount = row.unitPrice*row.procureQuantity;
      row.budgetAmount = budgetAmount;
    },
    /** 采购计划明细序号 */
    rowAProcurePlanDetailIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 采购计划明细添加按钮操作 */
    handleAddAProcurePlanDetail() {
      let obj = {};
      obj.productName = "";
      obj.productCategory = "";
      obj.largeCategoryCode = "";
      obj.middleCategoryCode = "";
      obj.smallCategoryCode = "";
      obj.specificationModle = "";
      obj.measurementUnit = "";
      obj.unitPrice = "";
      obj.procureQuantity = "";
      obj.budgetAmount = "";
      obj.procurePurpose = "";
      obj.productLineId = "";
      obj.remarks = "";
      this.aProcurePlanDetailList.push(obj);
    },
    /** 采购计划明细删除按钮操作 */
    handleDeleteAProcurePlanDetail() {
      if (this.checkedAProcurePlanDetail.length == 0) {
        this.$modal.msgError("请先选择要删除的采购计划明细数据");
      } else {
        const aProcurePlanDetailList = this.aProcurePlanDetailList;
        const checkedAProcurePlanDetail = this.checkedAProcurePlanDetail;
        this.aProcurePlanDetailList = aProcurePlanDetailList.filter(function(item) {
          return checkedAProcurePlanDetail.indexOf(item.index) == -1
        });
      }
    },
    /** 复选框选中数据 */
    handleAProcurePlanDetailSelectionChange(selection) {
      this.checkedAProcurePlanDetail = selection.map(item => item.index)
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["formData"].validate(valid => {
          if (valid) {
            this.formData.procurePlanDetailList = this.aProcurePlanDetailList;
            console.log(this.formData)
            addPlan(this.formData).then(response => {
              this.$modal.msgSuccess("新增成功");
              const obj = { path: "/procure/plan" };
              this.$tab.closeOpenPage(obj);
            });
          }
      });
    },

    /** 关闭按钮 */
    close() {
      const obj = { path: "/procure/plan" };
      this.$tab.closeOpenPage(obj);
    },
    // 获取当前时间
    getNowTime(isAll){
      let now = new Date();
      let year = now.getFullYear(); //获取完整的年份(4位,1970-????)
      let month = now.getMonth() + 1; //获取当前月份(0-11,0代表1月)
      let today = now.getDate(); //获取当前日(1-31)
      let hour = now.getHours(); //获取当前小时数(0-23)
      let minute = now.getMinutes(); //获取当前分钟数(0-59)
      let second = now.getSeconds(); //获取当前秒数(0-59)
      let nowTime = ''
      //返回年月日时分秒
      if(isAll){
        nowTime = year + '-' + this.fillZero(month) + '-' + this.fillZero(today) + ' ' + this.fillZero(hour) + ':' + this.fillZero(minute) + ':' + this.fillZero(second)
      }else{//返回年月日
        nowTime = year + '-' + this.fillZero(month) + '-' + this.fillZero(today)
      }
      return nowTime
    },
    // 给时间补零
    fillZero(str){
      let realNum
      if (str < 10) {
        realNum = '0' + str;
      } else {
        realNum = str;
      }
      return realNum;
    }

  }
}

</script>
